package com.letianpai.activity.photoalbum;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.letianpai.R;
import com.letianpai.adapter.photoalbum.PhotoGroupAdapter;
import com.letianpai.adapter.photoalbum.PhotoGroupInfo;
import com.letianpai.adapter.photoalbum.PhotoInfo;
import com.letianpai.common.client.HttpFileUploadClient;
import com.letianpai.common.client.ModelResult;
import com.letianpai.common.component.loading.LoadingDialog;
import com.letianpai.common.tool.DateTool;
import com.letianpai.common.tool.FileUtil;
import com.letianpai.db.entity.PictureInfo;

import java.io.File;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-9-26
 * Time: 下午1:46
 * 本地相册
 */
public class LocalAlbumActivity extends Activity {
    private TextView uploadTv;
    private LoadingDialog loadingDialog;
    private ListView photoManageLv;//本地相册
    private PhotoGroupAdapter photoGroupAdapter;
    private List<String> keyList = null;
    private String username, roomId, albumId, owner;
    private List<PhotoGroupInfo> groupInfoList = null;
    private List<PictureInfo> pictureList = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.local_album);
        photoManageLv = (ListView) findViewById(R.id.local_album_photo_lv);
        ImageButton backTv = (ImageButton) findViewById(R.id.top_back_ib);
        backTv.setOnClickListener(new BackOnClickListener());
        uploadTv = (TextView) findViewById(R.id.local_album_upload_tv);
        photoManageLv.setOnFocusChangeListener(null);
        photoManageLv.setOnHierarchyChangeListener(null);
        uploadTv.setOnClickListener(new UploadOnClickListener());
        Intent intent = getIntent();
        roomId = intent.getStringExtra("roomid");
        username = intent.getStringExtra("username");
        albumId = intent.getStringExtra("albumId");
        owner = intent.getStringExtra("owner");
        new AlbumAsyncTask().execute();

    }

    private void returnFinish() {
        Intent intent = new Intent();
        intent.putExtra("refresh", "create_album_return");
        setResult(Activity.RESULT_OK, intent);
        //成功跳转到添加照片页面
        finish();
    }

    class BackOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            returnFinish();
        }
    }

    private class UploadOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            pictureList = new ArrayList<PictureInfo>();
            for (PhotoGroupInfo groupInfo : groupInfoList) {
                for (PhotoInfo photo : groupInfo.getPhotoInfoList()) {
                    if (photo.isWhetherSelected()) {
                        PictureInfo picture = new PictureInfo();
                        picture.setId(String.valueOf(photo.getId()));
                        picture.setPicName(photo.getPhotoName());
                        picture.setPicPath(photo.getPhotoPath());
                        picture.setPicType("jpg");
                        picture.setPicMd5(FileUtil.getFileMD5(new File(photo.getPhotoPath())));
                        pictureList.add(picture);
                    }
                }
            }
            if (pictureList.size() < 1) {
                Toast.makeText(LocalAlbumActivity.this, "请您先选择照片", Toast.LENGTH_LONG).show();
            } else {
                new UploadTask().execute();
            }
        }
    }

    class UploadTask extends AsyncTask<String, Integer, Boolean> {
        //https://github.com/feicien/StudyDemo/commit/0ee6f1aed07bfcd55d070474cb188833034d6c30

        UploadTask() {
            loadingDialog = new LoadingDialog(LocalAlbumActivity.this);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomid", roomId);
            map.put("action", "upload");
            map.put("catid", albumId);
            map.put("username", username);
            map.put("num", String.valueOf(pictureList.size()));
            ModelResult<String> model = HttpFileUploadClient.doVeryLongPost("roomPhotoServlet", map, pictureList);
            if (model.isReturnResult()) {

                return Boolean.valueOf(true);
            } else {
                return Boolean.valueOf(false);
            }
        }

        @Override
        protected void onPostExecute(Boolean res) {
            super.onPostExecute(res);
            loadingDialog.dismiss();
            if (res.booleanValue()) {
                returnFinish();
            } else {
                Toast.makeText(LocalAlbumActivity.this, "服务忙，请您稍后再试", Toast.LENGTH_LONG).show();
            }
        }
    }


    class AlbumAsyncTask extends AsyncTask<String, Integer, List<PhotoGroupInfo>> {
        @Override
        protected void onPostExecute(List<PhotoGroupInfo> groupInfoList) {
            super.onPostExecute(groupInfoList);
            photoGroupAdapter = new PhotoGroupAdapter(LocalAlbumActivity.this, groupInfoList);
            photoManageLv.setAdapter(photoGroupAdapter);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        protected List<PhotoGroupInfo> doInBackground(String... params) {
            List<PhotoInfo> photoList = initPicture();
            groupInfoList = new ArrayList<PhotoGroupInfo>();
            for (String str : keyList) {
                PhotoGroupInfo groupInfo = new PhotoGroupInfo();
                groupInfo.setDate(str);
                List<PhotoInfo> photoChildList = new ArrayList<PhotoInfo>();
                for (PhotoInfo photo : photoList) {
                    if (str.equals(photo.getCreateDate())) {
                        photoChildList.add(photo);
                    }
                }
                groupInfo.setPhotoInfoList(photoChildList);
                groupInfoList.add(groupInfo);
            }
            return groupInfoList;
        }
    }

    //读取本地相册
    private List<PhotoInfo> initPicture() {
        Set<String> dateSet = new HashSet<String>();
        List<PhotoInfo> photoList = new ArrayList<PhotoInfo>();
        ContentResolver cr = this.getContentResolver();
//
//        Uri uri = Uri.parse("content://media/external/images/media");
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        // Thumbnails.EXTERNAL_CONTENT_URI   缩略图
        //标识，路径，大小，名称，类型，标题，创建时间、来源
        Cursor cursor = cr.query(uri, new String[]{"_id", "_data", "_size", "_display_name", "mime_type",
                "title", "datetaken", "bucket_display_name"}, null, null, "datetaken DESC");
        while (cursor.moveToNext()) {
//            String sourFrom = cursor.getString(cursor.getColumnIndex("bucket_display_name"));
//            if ("Camera".equals(sourFrom)) {
            PhotoInfo photo = new PhotoInfo();
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            photo.setId(id);
            photo.setPhotoName(cursor.getString(cursor.getColumnIndex("_display_name")));
            photo.setPhotoPath(cursor.getString(cursor.getColumnIndex("_data")));
            photo.setSize(cursor.getLong(cursor.getColumnIndex("_size")));
            photo.setMimeType(cursor.getString(cursor.getColumnIndex("mime_type")));
            photo.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            String createDate = DateTool.getDateByLongTime(cursor.getLong(cursor.getColumnIndex("datetaken")));
            photo.setCreateDate(createDate);
//            String[] projection = {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.DATA};
//            Cursor childCursor = getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, "image_id=" + id, null, null);
//            while (childCursor.moveToNext()) {
//                String thumPath = childCursor.getString(childCursor.getColumnIndex("_data"));
////                System.out.println("缩略图" + thumPath);
////                System.out.println("缩略图2" + childCursor.getString(childCursor.getColumnIndex("_id")));
////                System.out.println("主图" + id);
//                photo.setThumbnailPath(thumPath);
//            }
//            childCursor.close();
            photoList.add(photo);
            dateSet.add(createDate);
//            }
        }
        cursor.close();
        //调用排序通用类
//        SortList<PhotoInfo> sortList = new SortList<PhotoInfo>();
//        sortList.Sort(photoList, "getCreateDate", "date", "desc");
        keyList = new ArrayList<String>();
        for (String key : dateSet) {
            keyList.add(key);
        }
        Comparator<String> setComp = Collections.reverseOrder(); //降序
        Collections.sort(keyList, setComp);
        return photoList;
        //得到ContentResolver 对象
        // 图片的地址就包括MediaStore.Images.Media.INTERNAL_CONTENT_URI和
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI两个基础地址，
        // 其值分别是content://media/internal/images/media和
        // content://media/external/images/media，
        // 对应内部库和外部库地址
//        CREATE TABLE images (_id INTEGERPRIMARY KEY,_data TEXT,_size INTEGER,_display_name TEXT,mime_type TEXT,title
//                TEXT,date_added INTEGER,date_modified INTEGER,description TEXT,picasa_id TEXT,isprivate INTEGER,latitude DOUBL
//                E,longitude DOUBLE,datetaken INTEGER,orientation INTEGER,mini_thumb_magic INTEGER,bucket_id TEXT,bucket_displa
//                y_name TEXT);
//        Thumbnails表：这个表和images表是有直接关系的。主要存储图片的缩略图，Android为每一张保存进系统的图片文件都会自动生成一张缩略图文件。关于这一点还有一些特殊的技巧后面再讲。我们可以看一下这个表的结构：
//        CREATE TABLE thumbnails (_id INTEGERPRIMARY KEY,_data TEXT,image_id INTEGER,kind INTEGER,width INTEGER,height INTEGER);
//        ContentResolver cr = this.getContentResolver();
//        Uri uri = Uri.parse("content://media/external/images/media");
//        Cursor parentCursor = cr.query(uri, new String[]{"_id", "_data", "_size", "_display_name", "mime_type",
//                "title", "date_added", "date_modified", "description", "picasa_id", "isprivate", "latitude",
//                "longitude", "datetaken", "orientation", "mini_thumb_magic", "bucket_id", "bucket_display_name"}, null, null, null);
//        while (parentCursor.moveToNext()) {
//            System.out.println("输出的值");
//            System.out.println("_id:" + parentCursor.getString(0));
//            System.out.println("_data:" + parentCursor.getString(1));
//            System.out.println("_size:" + parentCursor.getString(2));
//            System.out.println("_display_name:" + parentCursor.getString(3));
//            System.out.println("mime_type:" + parentCursor.getString(4));
//            System.out.println("title:" + parentCursor.getString(5));
//            System.out.println("date_added:" + parentCursor.getString(6));
//            System.out.println("date_modified:" + parentCursor.getString(7));
//            System.out.println("description:" + parentCursor.getString(8));
//            System.out.println("picasa_id:" + parentCursor.getString(9));
//            System.out.println("isprivate:" + parentCursor.getString(10));
//            System.out.println("latitude:" + parentCursor.getString(11));
//            System.out.println("longitude:" + parentCursor.getString(12));
//            System.out.println("datetaken:" + parentCursor.getString(13));
//            System.out.println("orientation:" + parentCursor.getString(14));
//            System.out.println("mini_thumb_magic:" + parentCursor.getString(15));
//            System.out.println("bucket_id:" + parentCursor.getString(16));
//            System.out.println("bucket_display_name:" + parentCursor.getString(17));
//        09-27 11:22:52.663: INFO/System.out(22172): _id:533
//        09-27 11:22:52.663: INFO/System.out(22172): _data:/storage/emulated/0/.dxadcache/pos4ff54ca63cdba/mg53f732a674aaa.png
//        09-27 11:22:52.663: INFO/System.out(22172): _size:26999
//        09-27 11:22:52.663: INFO/System.out(22172): _display_name:mg53f732a674aaa.png
//        09-27 11:22:52.663: INFO/System.out(22172): mime_type:image/png
//        09-27 11:22:52.663: INFO/System.out(22172): title:mg53f732a674aaa
//        09-27 11:22:52.663: INFO/System.out(22172): date_added:1409620637
//        09-27 11:22:52.663: INFO/System.out(22172): date_modified:1409565767
//        09-27 11:22:52.663: INFO/System.out(22172): description:null
//        09-27 11:22:52.663: INFO/System.out(22172): picasa_id:null
//        09-27 11:22:52.663: INFO/System.out(22172): isprivate:null
//        09-27 11:22:52.667: INFO/System.out(22172): latitude:null
//        09-27 11:22:52.667: INFO/System.out(22172): longitude:null
//        09-27 11:22:52.667: INFO/System.out(22172): datetaken:1409565767000
//        09-27 11:22:52.667: INFO/System.out(22172): orientation:null
//        09-27 11:22:52.667: INFO/System.out(22172): mini_thumb_magic:null
//        09-27 11:22:52.667: INFO/System.out(22172): bucket_id:-1601507278
//        09-27 11:22:52.667: INFO/System.out(22172): bucket_display_name:pos4ff54ca63cdba
//        }

    }

}
